import errorCode from '@/util/errorCode'
import axios from 'axios'
import storage from 'store'
// 导入饿了么UI消息提醒
import {Message, Notification} from 'element-ui'
import {VueAxios} from './axios'
import store from "@/store";
import {getToken} from "@/util/auth";
// import { ACCESS_TOKEN } from '@/store/mutation-types'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 是否显示重新登录
export let isRelogin = {show: false};

const request = axios.create({
    baseURL: process.env.VUE_APP_API_ROOT,
    timeout: process.env["VUE_TIME_OUT"],
    responseType: 'json'
    // withCredentials: true
})

// 异常拦截处理器
const errorHandler = (error) => {
    console.error('err' + error)
    let {message} = error
    if (message === 'Network Error') {
        message = '后端接口连接异常'
        if (isRelogin.show) {
            store.dispatch('user/LogOut').then(() => {
                location.href = '/';
            }).catch(() => {
                outLogin()
            });
        }
    } else if (message.includes('timeout')) {
        message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
        message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Message.error({
        message: message,
        duration: 5 * 1000
    })
    //  return Promise.reject(error) //注释该行，否则接口请求失败会一直请求刷新错误数据，这里保证请求一次
}

// request interceptor
request.interceptors.request.use(config => {
    console.warn(config, 'request')
    const token = storage.get(store.state.user.token)
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
    // 如果 token 存在
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    if (getToken()) {
        config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
        let url = config.url + '?'
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName]
            var part = encodeURIComponent(propName) + '='
            // 修改漏洞
            if (value != null && typeof (value) !== 'undefined') {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        const params = propName + '[' + key + ']'
                        var subPart = encodeURIComponent(params) + '='
                        url += subPart + encodeURIComponent(value[key]) + '&'
                    }
                } else {
                    url += part + encodeURIComponent(value) + '&'
                }
            }
        }
        url = url.slice(0, -1)
        config.params = {}
        config.url = url
    }
    return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((res) => {
    console.warn(res.data, 'response')
    // 请求rul
    const requestUrl = res.config.url
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 401) {
        if (!isRelogin.show) {
            isRelogin.show = true;
            Notification({
                title: '系统提示',
                message: '登录状态已过期，请重新登录',
                type: 'warning',
                duration: 0,  // 设置为 0，表示通知不会自动关闭
            })
            store.dispatch('user/LogOut').then(() => {
                location.href = '/';
            }).catch(() => {
                outLogin()
            });
        }
        return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (code === 500) {
        Message({message: msg, type: 'error'})
        return Promise.reject(new Error(msg))
    } else if (code === 601) {
        Message({message: msg, type: 'warning'})
        return Promise.reject('error')
    } else if (code !== 200) {
        Notification.error({title: msg})
        return Promise.reject('error')
    } else {
        return res.data
    }
    return Promise.reject(msg)
}, errorHandler)

function outLogin() {
    isRelogin.show = false;
}

// 通用下载方法
let downloadLoadingInstance;

export function download(url, params, filename, config) {
    downloadLoadingInstance = Loading.service({
        text: "正在下载数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
    })
    return service.post(url, params, {
        transformRequest: [(params) => {
            return tansParams(params)
        }],
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        responseType: 'blob',
        ...config
    }).then(async (data) => {
        const isBlob = blobValidate(data);
        if (isBlob) {
            const blob = new Blob([data])
            saveAs(blob, filename)
        } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
            Message.error(errMsg);
        }
        downloadLoadingInstance.close();
    }).catch((r) => {
        console.error(r)
        Message.error('下载文件出现错误，请联系管理员！')
        downloadLoadingInstance.close();
    })
}

const installer = {
    vm: {},
    install(Vue) {
        Vue.use(VueAxios, request)
    }
}

export default request

export {
    installer as VueAxios,
    request as axios
}
